package com.jweb.plugins.c3p0;

import java.beans.PropertyVetoException;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jweb.framework.InstanceFactory;
import com.jweb.framework.core.ConfigHandle;
import com.jweb.framework.db.DataSourceFactory;
import com.jweb.framework.plugin.Plugin;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
 * C3p0Plugin
 * @author yuanqy
 *
 */
public class C3p0Plugin extends DataSourceFactory implements Plugin {
	Logger logger = LoggerFactory.getLogger(getClass());
	private ComboPooledDataSource dataSource;

	@Override
	public void init() {
		dataSource = new ComboPooledDataSource();
		dataSource.setJdbcUrl(ConfigHandle.getString("db.url"));
		dataSource.setUser(ConfigHandle.getString("db.username"));
		dataSource.setPassword(ConfigHandle.getString("db.password"));
		try {
			dataSource.setDriverClass(ConfigHandle.getString("db.driver"));
		} catch (PropertyVetoException e) {
			dataSource = null;
			logger.error("C3p0Plugin start error");
			throw new RuntimeException(e);
		}
		// ==public
//		dataSource.setMaxPoolSize(ConfigHandle.getInt("db.maxPoolSize", 1));
//		dataSource.setMinPoolSize(ConfigHandle.getInt("db.minPoolSize", 1));
//		dataSource.setInitialPoolSize(ConfigHandle.getInt("db.initialPoolSize", 1));
//		dataSource.setMaxIdleTime(ConfigHandle.getInt("db.maxIdleTime", 1));
//		dataSource.setAcquireIncrement(ConfigHandle.getInt("db.acquireIncrement", 1));
//		dataSource.setCheckoutTimeout(ConfigHandle.getInt("db.checkoutTimeout", 1));
		ConfigHandle.setProp(InstanceFactory.DS_FACTORY, getClass().getName());
	}

	@Override
	public void destroy() {
		dataSource.close();
	}

	@Override
	public DataSource getDataSource() {
		return dataSource;
	}

}
